import { EllipsisOutlined, PlusOutlined } from "@ant-design/icons";
import {
  Badge,
  Button,
  Drawer,
  Dropdown,
  Form,
  message,
  Popconfirm,
  Space,
  Tag,
} from "antd";
import { STable, SButton, SForm, InputType } from "@cnjingx/antd-components";
import { useEffect, useState } from "react";
import {
  addUser,
  deleteUser,
  fetchChangeUserStatus,
  fetchResetPwd,
  fetchUserList,
} from "@/api/modules/user.js";
import { checkResSuccess, encrypt, msg, processReq } from "@/utils/util.js";
import { isEmpty, to, toArray } from "wsp-toolkit";
import { mapToOptions, UserStatus } from "@/enums/dictionaries.js";
import { checkIdCard, checkPhoneNumber, checkPwd } from "@/utils/validator";
import { GetRoleList } from "@/api/modules/role";
import { useRequest } from "@/hooks/useRequest";

export function Component() {
  const [form] = Form.useForm();
  const [tableForm] = Form.useForm();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [roleList, setRoleList] = useState([]);

  const { run: changeUserStatus } = useRequest(fetchChangeUserStatus, {
    manual: true,
    onSuccess: () => {
      message.success("操作成功");
      loadUserList(page);
    },
  });

  const { run: AddNewUser } = useRequest(addUser, {
    manual: true,
    onSuccess: () => {
      message.success("新增成功");
      onClose();
      loadUserList(1);
    },
  });

  async function resetPwd(row) {
    const [err, data] = await processReq(
      fetchResetPwd({
        userId: row.userId,
        currentPassword: encrypt("1234.abcd"),
      }),
    );
    if (err) {
      msg.error(data);
      return;
    }
    message.success("操作成功");
  }

  async function loadRole() {
    const [err, data] = await processReq(
      GetRoleList({
        pageNum: 1,
        pageSize: 1000,
      }),
    );
    if (err) {
      msg.error(err);
      return;
    }
    setRoleList(data.data);
  }

  async function loadUserList(page, query = {}) {
    setLoading(true);
    const [err, data] = await processReq(
      fetchUserList({
        pageSize: 30,
        page,
        ...query,
      }),
    );
    setLoading(false);
    if (err) {
      msg.error(err);
      return;
    }
    setTotal(data.total);
    setDataSource(toArray(data.data));
    setPage(page);
  }

  // 初始化
  useEffect(() => {
    loadUserList(1);
    loadRole();
  }, []);

  async function handleDeleteUser(row) {
    setLoading(true);
    const [err] = await processReq(
      deleteUser({
        userId: row.userId,
      }),
    );
    setLoading(false);
    if (err) {
      msg.error(err);
      return;
    }
    message.success("删除用户成功");
    loadUserList(1);
  }

  const columns = [
    {
      title: "用户名称",
      dataIndex: "nickName",
    },
    {
      title: "用户账号",
      dataIndex: "userAccount",
    },
    {
      title: "证件号",
      dataIndex: "certNo",
      render: (text) => {
        if (typeof text !== "string" || isEmpty(text)) return "";
        return text.slice(0, 6) + "*".repeat(8) + text.slice(14);
      },
    },
    {
      title: "电话",
      dataIndex: "phone",
      render: (text) => {
        if (typeof text !== "string" || isEmpty(text)) return "";
        return text.slice(0, 3) + "*".repeat(4) + text.slice(7);
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (t) => {
        return String(t) === "1" ? (
          <Badge status="success" text={"启用"} />
        ) : (
          <Badge status="error" text={"停用"} />
        );
      },
    },
    {
      title: "操作",
      dataIndex: "_operations",
      render: (_, row) => {
        const status = String(row.status);

        return (
          <div>
            {row.userId !== "1" && (
              <SButton type="link" size="small" onClick={() => resetPwd(row)}>
                重置密码
              </SButton>
            )}
            {row.userId !== "1" && (
              <>
                <SButton
                  type="link"
                  size="small"
                  danger={status === "1"}
                  onClick={() =>
                    changeUserStatus({
                      userId: row.userId,
                      status: status === "1" ? "2" : "1",
                    })
                  }
                >
                  {status === "1" ? "停用" : "启用"}
                </SButton>
                <Popconfirm
                  title={"删除用户"}
                  description={"确认删除该用户？"}
                  okButtonProps={{ danger: true }}
                  onConfirm={() => {
                    handleDeleteUser(row);
                  }}
                >
                  <SButton type="link" size="small" danger>
                    删除
                  </SButton>
                </Popconfirm>
              </>
            )}
          </div>
        );
      },
    },
  ];

  const formItems = [
    {
      label: "账号",
      required: true,
      name: "userAccount",
    },
    {
      label: "密码",
      required: true,
      name: "password",
      inputType: InputType.password,
      rules: [
        {
          validator: (rule, value) => {
            if (isEmpty(value)) return Promise.resolve();
            const [ok, msg] = checkPwd(value);
            if (ok) return Promise.resolve();
            return Promise.reject(new Error(msg));
          },
        },
      ],
    },
    {
      label: "姓名",
      required: true,
      name: "nickName",
    },
    {
      label: "身份证号",
      required: true,
      name: "certNo",
      rules: [
        {
          validator: (rule, value) => {
            if (isEmpty(value)) return Promise.resolve();
            const [ok, msg] = checkIdCard(value);
            if (ok) return Promise.resolve();
            return Promise.reject(new Error(msg));
          },
        },
      ],
    },
    {
      label: "手机号",
      required: true,
      name: "phone",
      rules: [
        {
          validator: (rule, value) => {
            if (isEmpty(value)) return Promise.resolve();
            const [ok, msg] = checkPhoneNumber(value);
            if (ok) return Promise.resolve();
            return Promise.reject(new Error(msg));
          },
        },
      ],
    },
    {
      label: "账号状态",
      required: true,
      inputType: InputType.select,
      options: mapToOptions(UserStatus),
      name: "status",
      initialValue: "1",
    },
    {
      label: "角色",
      inputType: InputType.select,
      span: 2,
      name: "roleIds",
      options: roleList.map((x) => {
        return {
          label: x.roleName,
          value: x.roleId,
        };
      }),
      inputProps: {
        allowClear: true,
        mode: "multiple",
      },
    },
    {
      label: "备注",
      inputType: InputType.textArea,
      span: 2,
      name: "remark",
    },
  ];

  const onClose = () => {
    setOpen(false);
    form.resetFields();
  };

  const handleSubmit = async () => {
    const data = await form.validateFields();
    await AddNewUser({
      ...data,
      password: encrypt(data.password),
      userAccount: encrypt(data.userAccount),
    });
  };

  return (
    <div className={"flex flex-col"} style={{ height: "100%" }}>
      {/*<div style={{ marginBottom: 24 }}>用户管理</div>*/}
      <div style={{ flexGrow: 1 }}>
        <STable
          form={tableForm}
          formItems={[
            {
              label: "查询",
              name: "queryCondition",
            },
          ]}
          onSearch={() => {
            const v = tableForm.getFieldsValue();
            loadUserList(1, v);
          }}
          onReset={() => {
            tableForm.setFieldsValue({
              queryCondition: "",
            });
            loadUserList(1);
          }}
          columns={columns}
          page={page}
          onChange={(current) => {
            loadUserList(current);
          }}
          total={total}
          dataSource={dataSource}
          loading={loading}
          rowKey={"userId"}
        >
          <div
            className={"pb-8"}
            style={{ display: "flex", justifyContent: "flex-end" }}
          >
            <div>
              <SButton
                key="button"
                onClick={() => {
                  setOpen(true);
                }}
                type="primary"
              >
                新增
              </SButton>
            </div>
          </div>
        </STable>
      </div>

      <Drawer
        title={`新增用户`}
        placement="right"
        size={"large"}
        onClose={onClose}
        open={open}
        maskClosable={false}
        footer={
          <div className={"flex"} style={{ justifyContent: "flex-end" }}>
            <Space>
              <SButton onClick={onClose}>取消</SButton>
              <SButton type="primary" onClick={handleSubmit}>
                确认
              </SButton>
            </Space>
          </div>
        }
      >
        <SForm
          layout={"vertical"}
          formItems={formItems}
          columnRepeat={2}
          form={form}
        ></SForm>
      </Drawer>
    </div>
  );
}
